package com.qf.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qf.dao.QfCommentDao;
import com.qf.pojo.RedisKey;
import com.qf.pojo.respVo.BaseResp;
import com.qf.pojo.vo.QfComment;
import com.qf.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    QfCommentDao qfCommentDao;

    @Override
    public BaseResp findCourseCommentByCourseId(Integer id, Integer page, Integer size) {

        //1.判断redis中是否有该key
        Collection list =null;
        Boolean aBoolean = redisTemplate.hasKey(RedisKey.COURSECOMMENT+id.toString());
        Integer start=(page-1)*size;
        Integer end=start+size-1;
        Long total=null;
        if (aBoolean){
            list = redisTemplate.opsForZSet().reverseRange(RedisKey.COURSECOMMENT + id.toString(), start, end);
            total= redisTemplate.opsForZSet().size(RedisKey.COURSECOMMENT + id.toString());
        }else{
         List<QfComment>   commentlist = qfCommentDao.findCourseCommentByCourseId(id);
         if (commentlist==null||commentlist.size()==0){
             redisTemplate.opsForZSet().add(RedisKey.COURSECOMMENT+id.toString(),"null",0);
             redisTemplate.expire(RedisKey.COURSECOMMENT+id.toString(),1, TimeUnit.MINUTES);
         }
         for (QfComment comment:commentlist
                 ) {
                redisTemplate.opsForZSet().add(RedisKey.COURSECOMMENT+id.toString(),comment,comment.getScore());
            }
            list = redisTemplate.opsForZSet().reverseRange(RedisKey.COURSECOMMENT + id.toString(), start, end);
            total= redisTemplate.opsForZSet().size(RedisKey.COURSECOMMENT + id.toString());

        }
        return new BaseResp(1,"查询成功！",list,total);
    }
}
